Java Collection-HashSet, java-hashsetHashSet Overview
For a HashSet, it is implemented based on HashMap. The underlying layer uses HashMap to store elements. Therefore, if you are familiar with HashMap, it is easy to learn HashSet.
Let's take a look at the simplest construct
", Removeset);Clone a Retainset, the contents and set are identicalHashSet Retainset = (HashSet) set.clone ();Preserve "retainset, elements belonging to Otherset"Retainset.retainall (Otherset);Print RetainsetSystem.out.printf ("Retainset:%s\n", Retainset);Traverse HashSetfor (Iterator Iterator = Set.iterator ();Iterator.hasnext (); )System.out.printf ("Iterator:%s\n", Iterator.next ());Empty HashSetSet.clear ();Whether the output
Through source code analysis of HashMap and HashSet, the Hash storage mechanism set and reference are just like the reference type array. When we put Java objects into an array, not really put a Java object into an array, but put the object reference into an array. Each array element is a reference variable. Actually, HashSet
();
}
Public String toString ()
{
return "name[first=" + First + ", last=" + Last + "]";
}
}
public class HashSetTest2
{
public static void Main (string[] args)
{
hashsetnew hashset
Set.add (new Name ("abc", "123"));
Set.add (new Name ("abc", "456"));
SYSTEM.OUT.PRINTLN (set);
}
}
The above program provides a name class that overrides the Equals () and toString () two methods, both of which are judged by
();
}
Public String toString ()
{
return "name[first=" + First + ", last=" + Last + "]";
}
}
public class HashSetTest2
{
public static void Main (string[] args)
{
hashsetnew hashset
Set.add (new Name ("abc", "123"));
Set.add (new Name ("abc", "456"));
SYSTEM.OUT.PRINTLN (set);
}
}
The above program provides a name class that overrides the Equals () and toString () two methods, both of which are judged by
0. ReferencesIn-depth Java Collection Learning series: the implementation principle of HashSet1.HashSet Overview:HashSet implements the set interface, which is supported by a hash table (actually a hashmap instance). It does not guarantee the set's iteration order, especially it does not guarantee that the order is constant. This class allows the use of NULL elements. Duplicate elements are not allowed in
Java container HashMap and HashSet Learning
In Java learning, I saw the HashMap and HashSet classes. I learned the JDK source code and recorded the notes at the usage level (many companies have to ask the underlying layer for interviews.
Src.zip under source code jdk1.7
HashMap is a Key-Value Pair type. It provides a
:" +loadfactor); } //Read size and verify non-negative. intSize =S.readint (); if(Size ) { Throw NewInvalidobjectexception ("Illegal size:" +size); } //Set The capacity according to the size and load factor ensuring that//The HASHMAP is at least 25% full but clamping to maximum capacity.Capacity = (int) math.min (Size * math.min (1/loadfactor, 4.0f), hashmap.maximum_capacity); //Create backing HashMapMap = (((hashset Th
synchronous encapsulation!Set s = Collections.synchronizedSet(new HashSet(...));HashSet the iterator returned by iterator () is fail-fast.2. Inheritance relationships and APIsHashSet APIClasshashsetE>Java. lang. Object inheritorsJava. util. abstractcollectione> inheritors java . Utile> inheritors java.utile> type para
A HashSet Source CodeThe realization of HashSetFor HashSet, it is based on HASHMAP implementation, HashSet the bottom of the HashMap to save all the elements, so HashSet implementation is relatively simple, view HashSet source code, you can see the following code:
:9], r[count:-2]]hs is the R object with a package count of-3? false HS is the R object with a package count of 5? falseHS whether the package count is 9 R object? TrueFirst.count in the above program =-3; Because the count instance variable of the first R object in the HashSet collection was changedValue, which causes the R object to be the same as other objects in the collection. When you try to delete the R object of Count =-3, the HashSetThe has
IncreaseDeleteThe Remove method allows you to delete a specified element.Find*************************************************HashSet can neither use the index of 0 1 2 3 to determine the value of an element, nor use key to determine the value of an element*********************HashSet like this ["AA", "BB"] grow into such a data structure******************HashMap grow into such {a=123, B=hello}Jsonobject
:
Java.lang.Object
java.util.abstractcollection
HashSet and map relate to the following diagram:
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/
Constructor for HashSet
Default constructor public
hashset ()
///Collection Constructors public
Document directory
0. References
3. Instructions:
0. References
Go deep into Java Collection Learning Series: implementation principle of hashset1. hashset Overview:
Hashset implements the set interface, which is supported by a hash table (actually a hashmap instance. It does not guarantee the set iteration sequence; in particular, it does not ensure that the
instance: the elements themselves are not copied. * * The underlying actually calls Hashmap's clone () method, Gets the shallow copy of the hashmap, and sets it to Hashset. */ publicObject clone () {Try{HashSetSuper. Clone (); Newset.map= (hashmap) Map.clone (); returnnewset; } Catch(clonenotsupportedexception E) {Throw NewInternalerror (); } }}Related instructions
For the implementation principle of the related HashMap, please re
map.isempty (); } iterator: Returns an iterator that iterates over the elements in this setPublic iterator boolean remove (Object o): If the specified element is present in this set, remove itpublic boolean remove (Object o) { return Map.Remove (o) ==present; } int size (): Returns the number of elements in this set public int size () { return map.size (); }Third, HashSet application example codepublic class hashset
collection elements are enumerations of the Sesson type AEnumset es2=enumset.noneof (Sesson.class); -System.out.println (ES2);//[] - //adding elements manually the Es2.add (sesson.summer); - Es2.add (sesson.spring); -System.out.println (ES2);//[SPRING, SUMMER] - //creates a collection with the specified enumeration value +Enumset es3=Enumset.of (sesson.summer,sesson.winter); -System.out.println (ES3);//[SUMMER, WINTER] +Enumset es4=Enumset.range (sesson.spring, sesson.fall); ASy
Java Collection Framework HashSet and HASHMAP source Analysis
General Introduction
The reason why we put HashSet and hashmap together, because they have the same implementation in Java, the former is only a layer of packaging, that is, hashset inside a HashMap (adapter mod
The difference between HashMap and HashSet is the most frequently asked question in the Java interview. If not involved in the collection framework and multi-threaded interview, can be said to be incomplete. The problem of collection framework is not related to HashSet and hashmap, it can be said to be incomplete. Both HashMap and
HashSet is implemented based on the implementation--hashmap of the hash table in the Java class Library, unlike HashMap, which holds a single element instead of a key-value pair.In HashSet, use HashMap to store elements:private transient hashmapAs seen from this map type, it stores the hashset element as a HashMap key.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.